package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.vo.PageVo;
import com.etoak.entity.Dishes;
import com.etoak.vo.DishesVo;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-08-25
 */


@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {


    @Override
    public void addDish(Dishes dishes) {
        if(ObjectUtils.isNotEmpty(getByName(dishes.getName()))) {
            throw new CustomException("菜品名称重复");
        }

        dishes.setCreateTime(DateUtil.now());
        this.save(dishes);
    }

    private Dishes getByName(String name) {
        return lambdaQuery().eq(Dishes::getName, name).one();
    }

    @Override
    public PageVo<DishesVo> getList(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum, pageSize);
        List<DishesVo> dishesVos = baseMapper.getList(dishes);

        PageInfo<DishesVo> pageInfo = new PageInfo<>(dishesVos);
        return new PageVo<>(pageInfo.getTotal(), dishesVos);

    }

    @Override
    public void updateDish(int id, Dishes dishes) {
        if( ObjectUtils.isEmpty(this.getById(id))) {
            throw new CustomException("菜品不存在");
        }

        String name = dishes.getName();
        if(StringUtils.isNoneBlank(name)) {
            Dishes saveDishes = this.getByName(name);
            if( ObjectUtils.isNotEmpty(saveDishes) && !saveDishes.getId().equals(id)) {
                throw new CustomException("不能将名称修改为其他菜品的名称");
            }
        }

        dishes.setUpdateTime(DateUtil.now());
        dishes.setId(id);
        this.updateById(dishes);
    }

    @Override
    public void deleteDish(int id) {
        if( ObjectUtils.isEmpty(this.getById(id)) ) {
            throw new CustomException("食材不存在");
        }

        this.removeById(id);
    }
}
